package servlet;

import pojo.AccessControlDevice;
import pojo.Building;
import service.AccessControlDeviceService;
import service.BuildingService;
import service.impl.AccessControlDeviceServiceImpl;
import service.impl.BuildingServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;


@WebServlet(urlPatterns = "/list")
public class AllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求的字符编码
        request.setCharacterEncoding("UTF-8");

        //设置响应的字符编码
        response.setCharacterEncoding("UTF-8");

        //设置内容
        response.setContentType("text/html");
        //查询条件
        Integer buildingId = null;
        if(request.getParameter("buildingId")!=null  && !Objects.equals(request.getParameter("buildingId"), ""))
            buildingId = Integer.parseInt(request.getParameter("buildingId"));


        int pageIndex=1;//初始页数

        if (request.getParameter("pageIndex")!=null){
            pageIndex= Integer.parseInt(request.getParameter("pageIndex"));
        }

        int pageSize=2;//每页所查数量

        if (request.getParameter("pageSize")!=null){
            pageSize= Integer.parseInt(request.getParameter("pageSize"));
        }

        //查询所有
        AccessControlDeviceService accessControlDeviceService =new AccessControlDeviceServiceImpl();
        List<AccessControlDevice> page = accessControlDeviceService.page(pageIndex, pageSize, buildingId);


        int count = accessControlDeviceService.count();

        int pageCount=count/pageSize;//总页数
        if (count%pageSize!=0){
            pageCount+=1;
        }

        request.setAttribute("all",page);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("count",count);
        request.setAttribute("pageCount",pageCount);
        request.getRequestDispatcher("main.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
